package com.ykc.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

//定义切面代理类
public abstract class AspectProxy implements Proxy {

    private static final Logger logger = LoggerFactory.getLogger(AspectProxy.class);

    public final Object doProxy(ProxyChain proxyChain) throws Throwable{
        Object result=null;

        Method method=proxyChain.getTargetMethod();
        Object[] params=proxyChain.getMethodParams();

        begin();
        try {
            if (intercept(method,params)){
                before(method,params);
                //开始代理
                result=proxyChain.doProxyChain();
                after(method,params);
            }else {
                result=proxyChain.doProxyChain();
            }
        } catch (Exception e) {
            logger.error("proxy failure", e);
            error(method, params, e);
            throw e;
        } finally {
            end();
        }

        return result;
    }

    public void begin(){

    }

    /**
     * 切入点判断
     **/
    public boolean intercept(Method method,Object[] params) throws Throwable{
        return true;
    }

    //前置通知
    public void before(Method method,Object[] params) throws Throwable{

    }

    //后置通知
    public void after(Method method,Object[] params) throws Throwable{

    }

    //异常增强
    public void error(Method method,Object[] params,Throwable e){

    }

    //最终增强
    public void end(){

    }
}
